<?php
namespace app\admin\controller;
use service\JsonService;


/**
 * 上传控制器
 * Class Upload
 * @package app\admin\controller
 *
 */
class Upload extends AuthController
{
    public function image()
    {
        return $this->_upload('images');
    }

    /**
     * 视频上传
     * @Author   FW
     * @DateTime 2024-01-16
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function video()
    {
        return $this->_upload('videos');
    }

    /**
     * 音频上传
     * @Author   FW
     * @DateTime 2024-01-16
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function audio()
    {
        return $this->_upload('audios');

        // $file = request()->file('file');
        // $data = request()->post();
        // $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'audios');
        // if($info){
        //     $key = '/public/uploads/audios/' . str_replace('\\','/',$info->getSaveName());
        //     return json_encode([
        //         "code" => 200,
        //         "name" => $key,
        //         "url"  => request()->domain().$key,
        //     ]);
        // }

        // return json_encode([
        //     "code"=> 400,
        //     "state" => $file->getError()
        // ]);
    }

    /**
     * 上传
     * @Author   FW
     * @DateTime 2024-05-07
     * @Email    123763712@qq.com
     * @param    string           $dir [description]
     * @return   [type]                [description]
     */
    private function _upload( $dir = 'files' )
    {
        try {
            $file = request()->file('file');
            $content_type = $file->getInfo()['type'];
            $path = explode('.' , $file->getInfo()['name']);
            $name = sha1_file($file->getInfo()['tmp_name']) . '.' . $path[1];

            $res = \service\JSYService::upLoaderFile($file->getInfo()['tmp_name'] , $dir . '/' . $name , $content_type);
            if ( isset($res['ETag']) ) {
                return json_encode([
                    "code" => 200,
                    "name" => $dir . '/' . $name,
                    "url"  => \service\JSYService::FILE_DOMAIN . $dir . '/' . $name,
                ]);
            }
        } catch (\Exception $e) {
            return json_encode([
                "code"=> 400,
                "state" => $e->getMessage()
            ]);
        }

        return json_encode([
            "code"=> 400,
            "state" => $file->getError()
        ]);
    }
} //Class End


